package user

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	user3 "server/app/api/request/user"
	"server/base"
	group2 "server/common/models/group"
	pool2 "server/common/models/pool"
	user4 "server/common/models/user"
	"server/common/utils"
	"server/pkg/response"
)

var Mine = mine{}

type mine struct{}

func (*mine) Info(c *gin.Context) {
	userId := utils.GetUserId(c)
	var users user4.User
	base.App.Mysql.Object.Find(&users, "user_id = ?", userId)
	if users.UserId == 0 {
		response.NoAuth(c)
		return
	}

	var poolInfo pool2.PoolUserRegister
	base.App.Mysql.Object.Find(&poolInfo, "user_id = ?", userId)

	var userAuthStatus user4.UserAuth
	base.App.Mysql.Object.Model(&user4.UserAuth{}).Where("id = ?", userId).Find(&userAuthStatus)

	var group group2.GroupUser
	base.Mysql.Find(&group, "user_id = ? and status = ?", userId, group2.GroupStatusDoing)
	response.Success(c, gin.H{"user": users, "pool": poolInfo, "user_auth_status": userAuthStatus.Status, "group": group})
}

func (*mine) Update(c *gin.Context) {
	var req user3.UpdateUserReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	err = base.Mysql.Transaction(func(tx *gorm.DB) error {
		// 更新用户资料状态
		err = tx.Model(&user4.UserAuth{}).Where("id = ?", utils.GetUserId(c)).Update("status", "ok").Error
		if err != nil {
			return err
		}

		// 更新用户资料
		err = tx.Model(&user4.User{}).Where("user_id = ?", utils.GetUserId(c)).Updates(req.GetUserUpdates()).Error
		if err != nil {
			return err
		}

		// 更新用户内容
		err = tx.Model(&user4.UserIntro{}).Where("user_id = ?", utils.GetUserId(c)).Updates(map[string]interface{}{
			"main_photo": req.MainPhoto, "living_photo": req.GetLiving(),
		}).Error
		if err != nil {
			return err
		}
		return nil
	})

	if err != nil {
		response.Error(c, err.Error())
		return
	}

	response.Success(c, nil)
}

func (*mine) UpdateByField(c *gin.Context) {
	var req user3.UpdateUserByFieldReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	err = base.Mysql.Model(&user4.UserIntro{}).Where("user_id = ?", utils.GetUserId(c)).Update(req.Field, req.Message).Error
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	response.Success(c, gin.H{})
}

func (*mine) UpdateIntro(c *gin.Context) {
	var req user3.UpdateUserDetailReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.Error(c, err.Error())
		return
	}
	err = base.Mysql.Model(&user4.User{}).Where("user_id = ?", utils.GetUserId(c)).Updates(req.GetUserUpdates()).Error
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	response.Success(c, gin.H{})
}
